using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace cswavrec
{
    public class AudioPlayer
    {

        #region "Private properties, events and fields"

        private static WaveLib.WaveOutPlayer m_Player = null;
        private static byte[] m_PlayBuffer = null;
        private static Stream m_AudioStream = null;
        private static bool m_Repeat = false;

        #endregion

        #region "Public properties, events and fields"

        public static bool IsPlaying
        {
            get
            {
                return (m_Player != null);
            }
        }

        #endregion

        #region "Constructors"

        #endregion

        #region "private methods"

        private static void Filler(IntPtr data, int size)
        {
            if (m_Player == null) return;
            if (m_AudioStream == null)
            {
                StopPlay();

            }
            else
            {

                if (m_PlayBuffer == null || m_PlayBuffer.Length < size)
                    m_PlayBuffer = new byte[size];

                int n = 0;
                try
                {
                    n = m_AudioStream.Read(m_PlayBuffer, 0, size);
                }
                catch { }
                if (n == 0)
                {
                    if (m_Repeat)
                    {
                        m_AudioStream.Position = 0;
                    }
                    else
                    {
                        m_AudioStream.Close();
                        m_AudioStream = null;
                    }
                }
                for (int i = n; i < size; i++)
                {
                    m_PlayBuffer[i] = 0;
                }

                System.Runtime.InteropServices.Marshal.Copy(m_PlayBuffer, 0, data, size);
            }

        }

        #endregion

        #region "Public methods"

        public static void StartPlay(Stream aStream, bool Repeat)
        {
            if (aStream.CanRead)
            {
                aStream.Position = 0;
                m_AudioStream = aStream;
                m_Repeat = Repeat;
                WaveLib.WaveFormat fmt = new WaveLib.WaveFormat(12000, 16, 1);
                m_Player = new WaveLib.WaveOutPlayer(-1, fmt, 16384, 3, new WaveLib.BufferFillEventHandler(Filler));
            }
        }

        public static void StopPlay()
        {
            if (IsPlaying)
            {
                try
                {
                    m_Player.Dispose();
                    m_Player = null;
                }
                catch (Exception ex)
                {
                }
            }
        }

        #endregion

    }
}
